<template>
  <basic-container class="userPage" v-loading="loading" element-loading-text="数据加载中...">
    <dataList
      ref="crud"
      :pageInfo="pager"
      :listData="tableData"
      :menuList=" [{ add: '添加' }]"
      :listLayout="['menu']"
      @menu-click="handleMenuClick"
    >
      <div slot="buttons" class="btns">
        <el-button size="small" type="primary" @click="handleMenuClick('add')">新增</el-button>
        <el-button size="small" type="primary" @click="handleMenuClick('import')">导入</el-button>
        <v-dialog v-if="updialogShow" :show.sync="updialogVisible" width="800px" title="文件上传">
          <v-upload
            ref="fileUpload"
            modelType="file"
            type="file"
            @onSuccess="uploadOnSuccess"
            @onError="onError"
            :autoLoadFiles="false"
            :isView="false"
            multiple
            v-model="fileList"
          />
          <span slot="foot">
            <el-button @click="uphandleCancel">取 消</el-button>
            <el-button v-throttle="[uploadCommit]">上 传</el-button>
          </span>
          <div class="upload-error-list" v-if="errorList.length">
            <h5>失败原因：</h5>
            <div class="error-list">
              <p v-for="(err,index) in errorList" :key="index">{{err.errorMsg}}</p>
            </div>
          </div>
        </v-dialog>
        <el-button size="small" type="primary" @click="handleMenuClick('export')">下载隔离点工作人员信息模板</el-button>
      </div>
      <div class="user-top" slot="customFilter">
        <el-form
          class="form-wrap"
          label-position="left"
          size="small"
          :model="searchFrom"
          label-width="85px"
        >
          <el-form-item label="行政区域：" prop="delFlag">
            <el-popover placement="bottom" width="400" trigger="click" v-model="delFlagVisibleArea">
              <!-- <el-input
                v-halfCharCode
                placeholder="输入关键字进行过滤"
                v-model="filterText"
              />-->

              <el-tree
                class="filter-tree"
                :data="treeAreaData"
                lazy
                :load="loadNode"
                :props="defaultAreaProps"
                :filter-node-method="filterNode"
                :expand-on-click-node="false"
                @node-click="handleCheckChangeArea"
                style="max-height:400px;overflow-y: auto;"
                ref="tree"
              ></el-tree>
              <el-input
                v-halfCharCode
                slot="reference"
                maxlength="30"
                placeholder="请选择行政区域"
                v-model="searchFrom.divisionName"
                :suffix-icon="
                  delFlagVisibleArea ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                "
                clearable
              />
            </el-popover>
          </el-form-item>
          <el-form-item label="姓名：" prop="realName">
            <el-input
              v-halfCharCode
              maxlength="30"
              placeholder="请输入姓名"
              v-model="searchFrom.realName"
              clearable
            />
          </el-form-item>
          <el-form-item label="手机号码：" prop="phone">
            <el-input
              v-halfCharCode
              maxlength="20"
              placeholder="请输入手机号码"
              v-model="searchFrom.phone"
              clearable
            />
          </el-form-item>
          <el-form-item label="角色：" prop="roleNameList">
            <el-select clearable placeholder="请选择状态" v-model="searchFrom.roleNameList">
              <el-option
                v-for="item in rolesOptions"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人员类型" prop="queryJobId">
            <el-cascader
              style="width:100%"
              clearable
              v-model="searchFrom.queryJobId"
              :props="personSearchTypeprops"
              :options="personOptions"
              :show-all-levels="false"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="用户名：" prop="username">
            <el-input maxlength="20" placeholder="请输入用户名" v-model="searchFrom.username" clearable />
          </el-form-item>
          <el-form-item label="状态：" prop="lockFlag">
            <el-select clearable placeholder="请选择状态" v-model="searchFrom.lockFlag">
              <el-option
                v-for="item in lockFlagDicData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="user-btn">
          <el-button type="primary" size="small" class="btn" @click="handleFilter">查询</el-button>
          <el-button size="small" class="btn" @click="handleReset">重置</el-button>
        </div>
      </div>
      <el-table :data="tableData" align="left" ref="multipleTable">
        <el-table-column label="序号" type="index" :index="getIndex" width="55" />
        <el-table-column label="姓名" width="100" prop="realName" />
        <el-table-column label="行政区域" width="140" prop="divisionName" />
        <el-table-column label="手机号" width="140" prop="phone" />
        <el-table-column label="隔离点名称" prop="roleList">
          <template slot-scope="scope">
            <div v-if="scope.row.hotelBaseInfoVoList.length && scope.row.hotelBaseInfoVoList[0]">
              <el-tooltip
                v-for="item in scope.row.hotelBaseInfoVoList"
                :key="item.hotelName"
                placement="top"
                :content="item.hotelName"
              >
                <el-tag size="medium">{{ item.hotelName }}</el-tag>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="人员类型" prop="jobIdList" class-name="table-person-type">
          <template slot-scope="scope">
            <div
              v-for="item in scope.row && scope.row.jobIdList && scope.row.jobIdList.map(b=>personOptionsFlab.find(a=>a.jobId===b.jobId))"
              :key="item&&item.jobId"
            >
              <el-tag>{{item&&item.jobName}}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色" prop="roleList">
          <template slot-scope="scope">
            <!-- <div style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"> -->
            <el-tooltip
              v-for="item in scope.row.roleList"
              :key="item.$index"
              placement="top"
              :content="item.roleName"
            >
              <el-tag size="medium">{{ item.roleName }}</el-tag>
            </el-tooltip>
            <!-- </div> -->
          </template>
        </el-table-column>
        <el-table-column label="用户名" width="140" prop="username" />
        <el-table-column label="状态" width="80" prop="lockFlag">
          <template slot-scope="scope">
            <el-tooltip
              placement="top"
              :content="getCardTypeValue(scope.row.lockFlag, lockFlagDicData)"
            >
              <el-tag size="medium">
                {{
                getCardTypeValue(scope.row.lockFlag, lockFlagDicData)
                }}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column width="250" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="handleUpdate(scope.row, scope.index)">编辑</el-button>
            <el-button type="text" @click="deletes(scope.row, scope.index)">删除</el-button>
            <el-button type="text" @click="resetPassword(scope.row)">密码重置</el-button>
            <el-button type="text" @click="unLock(scope.row, scope.index)">解除锁定</el-button>
          </template>
        </el-table-column>
      </el-table>
    </dataList>

    <reset-password ref="resetPassword" />
    <v-dialog
      :title="isEdit ? '编辑' : '新增'"
      :show.sync="dialogVisible"
      class="dialogForm"
      width="1000px"
      @onSuccess="onSuccess"
      v-loading="dialogLoading"
      element-loading-text="正在保存..."
      v-if="dialogVisible"
      @beforeClose="beforeClose"
    >
      <el-form
        ref="tableOptionForm"
        class="form-wrap"
        :rules="tableOption_rules"
        :model="tableOption"
        label-width="140px"
        label-position="left"
      >
        <el-form-item label="行政区域：" prop="delFlag">
          <el-popover
            placement="bottom"
            width="400"
            trigger="click"
            v-model="delFlagVisibleAreadiog"
          >
            <el-tree
              class="filter-tree"
              lazy
              :data="treeAreaData"
              :load="loadNode"
              :props="defaultAreaProps"
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              @node-click="handleCheckChangeAreadiog"
              ref="tree"
            ></el-tree>
            <el-input
              v-halfCharCode
              slot="reference"
              filterable
              maxlength="30"
              :disabled="hotelDis"
              placeholder="请选择行政区域"
              v-model="tableOption.divisionName"
              :suffix-icon="
                  delFlagVisibleArea ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                "
              clearable
            />
          </el-popover>
        </el-form-item>
        <el-form-item label="所属隔离点" prop="isolationId">
          <el-select
            clearable
            filterable
            :disabled="hotelDis"
            placeholder="请选择隔离点"
            v-model="tableOption.isolationId"
            @change="hotelChange"
          >
            <el-option
              v-for="item in hotelIdDict"
              :key="item.hotelBaseInfoId"
              :label="item.hotelName"
              :value="item.hotelBaseInfoId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input
            v-halfCharCode
            maxlength="20"
            minlength="2"
            placeholder="请输入姓名"
            v-model="tableOption.realName"
          />
        </el-form-item>
        <el-form-item label="证件类型" prop="cardType">
          <el-select clearable placeholder="请选择证件类型" v-model="tableOption.cardType">
            <el-option
              v-for="item in getDict('card_type')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码" prop="idCard">
          <el-input
            v-halfCharCode
            type="text"
            maxlength="18"
            minlength="18"
            autocomplete="new-password"
            placeholder="请输入证件号码"
            v-model="tableOption.idCard"
            @blur="changeFn"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-halfCharCode placeholder="请输入手机号" v-model="tableOption.phone" ref="phone" />
        </el-form-item>

        <el-form-item label="工作单位" prop="workUnit">
          <el-input v-halfCharCode placeholder="请输入工作单位" v-model="tableOption.workUnit" />
        </el-form-item>

        <el-form-item label="职务" prop="job">
          <el-input v-halfCharCode placeholder="请输入职务" v-model="tableOption.job" />
        </el-form-item>
        <el-form-item label="人员类型" prop="jobIdList">
          <el-cascader
            class="form-cascader"
            ref="searchType"
            v-model="tableOption.jobIdList"
            :props="personTypeprops"
            :options="personOptions"
            :show-all-levels="false"
            @change="personTypeChange"
          >
            <!-- <div
              class="custom_cascader_node"
              slot-scope="{ node, data }"
              @click="cascaderHandler(node,data)"
            >
              <span>{{node.label}}</span>
            </div>-->
          </el-cascader>
        </el-form-item>
        <el-form-item label="是否开通系统用户" prop="isSysUser">
          <el-radio-group size="small" v-model="isSysUser">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户名" prop="username" v-show="isSysUser">
          <el-input
            v-halfCharCode
            maxlength="20"
            minlength="3"
            class="light"
            placeholder="默认不填，即为手机号"
            v-model="tableOption.username"
            :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password" v-show="isSysUser">
          <el-input
            v-halfCharCode
            type="password"
            class="light"
            autocomplete="new-password"
            placeholder="默认不填，即为证件号码后六位"
            v-model="tableOption.password"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role" v-if="isSysUser">
          <el-select clearable placeholder="请选择角色" v-model="tableOption.role" multiple>
            <el-option
              v-for="item in rolesOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            ></el-option>
          </el-select>
          <div v-show="!tableOption.role.length" class="roleTip">角色为空时,该工作人员将在系统无任何操作权限</div>
        </el-form-item>
        <el-form-item label="状态" prop="lockFlag">
          <el-radio-group v-model="tableOption.lockFlag" size="small">
            <el-radio label="0">有效</el-radio>
            <el-radio label="2">无效</el-radio>
            <el-radio label="9">锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--   <el-form-item label="创建时间" prop="createTime" v-if="isEdit">
          <el-input
            v-halfCharCode
            maxlength="20"
            minlength="3"
            placeholder="请输入创建时间"
            v-model="tableOption.createTime"
            :disabled="isEdit"
          />
        </el-form-item>-->
      </el-form>
      <span slot="foot">
        <el-button v-throttle="[commit]">保 存</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </span>
    </v-dialog>
  </basic-container>
</template>

<script>
import {
  addObj,
  delObj,
  putUser,
  getDetails,
  getHotelList,
} from "~/admin/api/user";
import {
  fetchList,
  getAreaNameById,
  validatePhoneUnique,
  getPersonType,
  checkID,
} from "~/views/yq-personnel/api/staffMamge.js";
import { deptRoleList } from "~/admin/api/role";
import { fetchTree } from "~/admin/api/dept";
import { getDivision } from "@/admin/api/division";
import { UnLock } from "~/api/login";
import resetPassword from "./reset-password";
import { validateIdNo, validatePass } from "~/utils/validate.js";
import { getDict } from "@/utils";
export default {
  name: "user",
  provide() {
    return {
      initList: this.getListData,
    };
  },
  beforeMount() {
    this._getPersonType(); // 获取人员类型树
    this.getListData();
    this.getNodeData();
    this.getHotelList(); //获取隔离点下拉
  },
  mounted() {
    // 根据用户信息给隔离点赋值和控制是否可选
  },
  computed: {
    options() {
      return getDict("person_type").filter(
        (item) => item.value.length == 2 && !["07", "08"].includes(item.value)
      );
    },
  },
  components: { resetPassword },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    dialogVisible(val) {
      if (val) {
        this.getUser();
      }
    },
    isSysUser(val) {
      if (!val) {
        this.tableOption.username = "";
        this.tableOption.password = "";
        this.tableOption.role = [];
      }
    },
  },
  data() {
    let validateUsername = (rule, value, callback) => {
      if (value) {
        getDetails(value).then((response) => {
          if (this.isEdit) callback();
          let result = response.data.data;
          if (result !== null) {
            callback(new Error("用户名已经存在"));
          } else {
            callback();
          }
        });
      } else {
        callback();
      }
    };
    let checkPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入联系方式"));
      } else {
        const reg = /^(1\d{10})$/;
        if (reg.test(value)) {
          validatePhoneUnique({
            phone: value,
            userId: this.currentUserId,
          }).then((res) => {
            if (!res.data.data) {
              callback(new Error("手机号重复"));
            }
            callback();
          });
        } else {
          return callback(new Error("请输入正确的电话"));
        }
      }
    };
    return {
      prePersonTypes: [],
      currentUserId: "",
      hotelDis: false,
      tableData: [],
      // 请求参数
      params: {
        current: 1,
        size: 10,
      },
      // 分页
      pager: {
        total: 0, // 总页数
        current: 1, // 当前页数
        size: 10, // 每页显示多少条
      },
      hotelIdDict: [],
      // 页面loading
      loading: false,
      dialogLoading: false,
      //状态对应值
      lockFlagDicData: [
        {
          label: "有效",
          value: "0",
        },
        {
          label: "无效",
          value: "2",
        },
        {
          label: "锁定",
          value: "9",
        },
      ],
      //搜索参数
      searchFrom: {},
      //角色
      rolesOptions: [],
      // 人员类型
      personOptions: [],
      personOptionsFlab: [],
      yesornoOptions: [],
      //行政部门下拉框
      treeAreaData: [],
      filterText: "",
      delFlag: "",
      delFlagArea: "",
      delFlagAreadiog: "",
      delFlagVisible: false,
      delFlagVisibleArea: false,
      delFlagVisibleAreadiog: false,
      defaultProps: {
        children: "children",
        label: "name",
      },
      defaultAreaProps: {
        children: "children",
        label: "divisionName",
      },
      personTypeprops: {
        multiple: true,
        checkStrictly: true,
        value: "jobId",
        // label: "jobName",
        children: "sysJobList",
      },
      personSearchTypeprops: {
        value: "jobId",
        label: "jobName",
        children: "sysJobList",
        checkStrictly: true,
        leaf: "jobCode",
      },
      //弹框标志
      dialogVisible: false,

      //是否编辑
      isEdit: false,
      //弹框表单
      tableOption: {
        realName: "",
        idCard: "",
        username: "",
        password: "",
        phone: "",
        role: [],
        lockFlag: "0",
        createTime: "",
      },
      isSysUser: 0,
      updialogVisible: false,
      updialogShow: false,
      fileList: [],
      errorList: [],
      //弹框表单校验
      tableOption_rules: {
        isolationId: [
          { required: true, message: "请选择隔离点", trigger: "blur" },
        ],
        realName: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        idCard: [
          { required: true, message: "请输入证件号码", trigger: "blur" },
          { validator: this.idCardValidate, trigger: "blur" },
        ],
        username: [
          { required: false, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
          { validator: validateUsername, trigger: "blur" },
        ],
        password: [
          { required: false, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
        lockFlag: [{ required: true, message: "请选择状态", trigger: "blur" }],
        jobIdList: [
          { required: true, message: "请选择人员类型", trigger: "blur" },
        ],
        cardType: [
          { required: true, message: "请选择证件类型", trigger: "change" },
        ],
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
    };
  },
  updated() {
    // this.tableOption.lockFlag = "0";
  },
  methods: {
    changeFn() {
      var _this = this;
      checkID({
        cardId: this.tableOption.idCard,
        hotelBaseInfoId: this.tableOption.isolationId,
      }).then((res) => {
        var reData = res.data.data;
        var uName = reData.realName;
        var address = reData.hotelBaseInfoVoList[0].hotelName;
        this.$confirm(
          `该证件号已经为"${address}"隔离点工作人员，是否添加"${uName}"为当前隔离点工作人员`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            _this.handleUpdate(reData, "", "add");
          })
          .catch(() => {});
      });
    },
    async _getPersonType() {
      await getPersonType().then((res) => {
        function typeMap(result) {
          let getType = (data) => {
            data.forEach((item) => {
              if (item.sysJobList && item.sysJobList.length > 0) {
                item.label = item.jobName;
                item.disabled = true;
                // item.readonly=true
                item.sysJobList = getType(item.sysJobList);
              } else {
                let str = "";
                item.isEnterRedZone && (str += "允许进入红区，");
                item.isEnterYellowZone && (str += "允许进入黄区，");
                item.isEnterGreenZone && (str += "允许进入绿区");
                item.label = `${item.jobName}（${str}）`;
                delete item.sysJobList;
              }
            });
            return data;
          };
          return getType(result);
        }

        this.personOptions = typeMap(res.data.data);
        const that = this;
        this.personOptionsFlab = [];
        function getPersonOptions(data) {
          data.forEach((a) => {
            if (a.sysJobList && a.sysJobList.length > 0) {
              getPersonOptions(a.sysJobList);
            }
            that.personOptionsFlab.push(a);
          });
        }
        getPersonOptions(res.data.data);
      });
    },
    hotelChange(val) {
      this.hotelIdDict.map((item) => {
        if (item.hotelBaseInfoId == val) {
          console.log(item);
          getAreaNameById(item.belongto).then((res) => {
            let data = res.data.data;
            this.$set(this.tableOption, "divisionName", data.divisionName);
            this.$set(this.tableOption, "division", item.belongto);
          });
        }
      });
    },
    async loadNode(node, resolve) {
      let data = [];
      const response = await getDivision({
        lazy: true,
        parentId: node.data.divisionCode ? node.data.divisionCode : "000000",
      });
      data = response.data.data;
      resolve(data);
    },
    // 获取列表
    getListData(params = {}) {
      this.loading = true;
      let requestData = { ...this.params, ...params };
      fetchList(requestData)
        .then((res) => {
          const { current, size, total, records } = res.data.data;
          this.tableData = records;
          this.params = requestData;
          this.pager = { total, current, size };
        })
        .finally(() => {
          this.loading = false;
        });
    },
    getHotelList() {
      // 获取隔离点下拉
      getHotelList().then((res) => {
        this.hotelIdDict = res.data.data;
      });
    },

    // 编辑
    async handleUpdate(row, index, type) {
      var rowEdit = JSON.parse(JSON.stringify(row));
      this.isEdit = true;
      this.dialogVisible = true;
      this.currentUserId = rowEdit.userId;
      this.yesornoOptions = getDict("yesorno");
      const oldTableOption = this.tableOption;
      if (type === "add") {
        const { isolationId, divisionName, ...others } = rowEdit;
        this.tableOption = {
          isolationId: oldTableOption.isolationId,
          divisionName: oldTableOption.divisionName,
          ...others,
        };
      } else {
        this.tableOption = rowEdit;
        this.$set(
          this.tableOption,
          "isolationId",
          rowEdit.hotelBaseInfoVoList[0].hotelBaseInfoId
        );
        this.$set(this.tableOption, "divisionName", rowEdit.divisionName);
      }
      this.$set(this.tableOption, "job", rowEdit.job);
      this.$set(this.tableOption, "workUnit", rowEdit.workUnit);

      this.$set(this.tableOption, "roleType", rowEdit.roleType);
      this.$set(this.tableOption, "isEnterRedZone", rowEdit.isEnterRedZone);
      this.$set(this.tableOption, "division", rowEdit.divisionCode);
      this.$set(
        this.tableOption,
        "role",
        rowEdit.roleList.map((item) => item.roleId)
      );
      // 转换角色用于返显
      let jobIdList = [].concat(rowEdit.jobIdList);
      let tempList = [];
      jobIdList.forEach((v) => {
        tempList.push(this.getFamilyTree(this.personOptions, v.jobId));
      });
      this.tableOption.jobIdList = tempList;
      // this.$set(this.tableOption, "jobIdList", rowEdit.jobIdList);
      if (rowEdit.username) {
        this.isSysUser = true;
      } else {
        this.isSysUser = false;
      }
    },
    // 删除
    deletes(row, index) {
      this.$confirm(
        "此操作将永久删除该用户(用户名:" + row.username + "), 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        delObj(row.userId)
          .then(() => {
            this.getListData();
            this.$notify.success("删除成功");
            this.$forceUpdate();
          })
          .catch(() => {
            this.$notify.error("删除失败");
          });
      });
    },
    // 密码重置
    resetPassword(row) {
      this.$refs.resetPassword.show(row);
    },
    // 解除锁定
    unLock(row, index) {
      this.$confirm(
        "此操作将(用户名:" + row.username + ")解除登录锁定, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        UnLock(row.userId)
          .then(() => {
            this.getListData();
            this.$notify.success("解除成功");
          })
          .catch(() => {
            this.$notify.error("解除失败");
          });
      });
    },
    // 添加
    handleCreate() {
      this.dialogVisible = true;
      this.yesornoOptions = getDict("yesorno");
    },
    getDict(type) {
      return getDict(type);
    },
    // 下拉框取值
    getCardTypeValue(num, sum) {
      let arr = sum.filter((e) => e.value === num);
      if (arr.length > 0) {
        return arr[0].label;
      } else {
        return num;
      }
    },
    // 获取角色
    getNodeData() {
      deptRoleList().then((response) => {
        this.rolesOptions = response.data.data.filter((item) => {
          return !item.roleCode.startsWith("SYS_");
        });
      });
    },

    // 获取用户信息
    getUser() {
      let userInfo = JSON.parse(
        JSON.parse(sessionStorage.getItem("dbl-user")).content
      );

      if (userInfo.isolationId) {
        this.tableOption.isolationId = userInfo.isolationId;
        this.hotelDis = true;
        // 自动赋值区域
        this.tableOption.division = userInfo.division;
        this.tableOption.divisionName = userInfo.divisionName;
      }

      console.log(this.tableOption.isolationId);
    },
    // 菜单点击监听
    handleMenuClick(type) {
      switch (type) {
        case "add":
          this.handleCreate();
          break;
        case "import":
          // 导入
          this.updialogShow = true;
          this.updialogVisible = true;
          this.errorList = [];
          break;
        case "export":
          //  导出模板
          this.publicExport("隔离点工作人员信息模板", "/admin/user/download");
          break;
      }
    },
    //文件上传
    async uploadOnSuccess(response, file, fileList) {
      if (fileList === undefined || fileList.length <= 0) {
        this.$message.error("请选择要上传的文件！");
      } else {
        this.$message.success(response.msg);
        this.updialogVisible = false;
        this.updialogShow = false;
      }
    },
    onError(err) {
      // 上传失败
      this.errorList = err.data || [];
      // this.$message.success(err.msg);
    },
    //确定
    uploadCommit() {
      this.$refs.fileUpload.submit("/admin/user/excelHotelUserImport");
    },
    // 取消
    uphandleCancel() {
      this.updialogVisible = false;
      this.updialogShow = false;
    },
    // 搜索
    handleFilter() {
      if (this.searchFrom.divisionName === "") {
        this.searchFrom.division = "";
      }
      let queryJobId = this.searchFrom.queryJobId;
      if (Array.isArray(queryJobId)) {
        this.searchFrom.queryJobId = queryJobId[queryJobId.length - 1];
      }
      this.getListData(this.searchFrom);
    },
    // 重置
    handleReset() {
      this.searchFrom.realName = "";
      this.searchFrom.username = "";
      this.searchFrom.delFlag = "";
      this.searchFrom.lockFlag = "";
      this.searchFrom.roleNameList = "";
      this.searchFrom.divisionName = "";
      this.searchFrom.division = "";

      this.getListData(this.searchFrom);
    },
    //图片上传并保存
    async onSuccess() {
      this.dialogLoading = true;
      if (this.isEdit) {
        const res = await putUser(this.tableOption);
        if (res.data.code === 0) {
          this.handleCancel(true);
          this.$notify.success("修改成功");
          this.dialogLoading = false;
        } else {
          this.dialogLoading = false;
          this.handleCancel();
          this.$notify.error("修改失败");
        }
      } else {
        const res = await addObj(this.tableOption);
        if (res.data.code === 0) {
          this.handleCancel();
          this.$notify.success("创建成功");
          this.dialogLoading = false;
        } else {
          this.dialogLoading = false;
          this.handleCancel();
          this.$notify.error("创建失败");
        }
      }
      this.handleFilter();
    },
    //保存前校验
    commit() {
      this.$refs.tableOptionForm.validate((valid) => {
        //点击保存时，“角色类型”自动设为“工作人员”，“角色”自动绑定“信息员”角色
        this.tableOption.roleType = "10";
        // this.tableOption.role = ["13"];
        this.tableOption.username = this.tableOption.phone;
        if (valid) {
          this.tableOption.$lockFlag = this.getCardTypeValue(
            this.tableOption.lockFlag,
            this.lockFlagDicData
          );
          if (this.tableOption.jobIdList.length) {
            for (const key in this.tableOption.jobIdList) {
              let item = this.tableOption.jobIdList[key];
              if (Array.isArray(item)) {
                this.tableOption.jobIdList[key] = item[item.length - 1];
              }
            }
          }
          this.tableOption.hotelBaseInfoIdList = [this.tableOption.isolationId];
          // this.$refs.avatarsUpload.submit();
          this.onSuccess();
        }
      });
    },
    //取消
    handleCancel(updata = false) {
      Object.keys(this.tableOption).forEach((key) => {
        if (this.tableOption[key]) {
          if (this.tableOption[key] instanceof Array) {
            this.tableOption[key] = [];
          } else if (
            typeof this.tableOption[key] === "string" ||
            typeof this.tableOption[key] === "number"
          ) {
            this.tableOption[key] = "";
          }
        }
      });
      this.isEdit = false;
      this.dialogVisible = false;
      this.isSysUser = "";
      if (!updata) {
        this.getListData();
      }
    },
    beforeClose(done) {
      this.handleCancel();
      this.currentUserId = null;
    },

    getFamilyTree(arr1, jobId) {
      // 获取当前节点及父节点的code
      var temp = [];
      var forFn = function (arr, jobId) {
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i];
          if (item.jobId === jobId) {
            temp.unshift(item.jobId);
            forFn(arr1, item.parentJobId);
            break;
          } else {
            if (item.sysJobList) {
              forFn(item.sysJobList, jobId);
            }
          }
        }
      };
      forFn(arr1, jobId);
      return temp;
    },
    // 部门过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleCheckChangeArea(data) {
      this.delFlagArea = data.divisionCode;
      this.$set(this.searchFrom, "divisionName", data.divisionName);
      this.$set(this.searchFrom, "division", data.divisionCode);
      this.delFlagVisibleArea = false;
    },
    handleCheckChangeAreadiog(data) {
      this.delFlagAreadiog = data.divisionCode;
      this.$set(this.tableOption, "divisionName", data.divisionName);
      this.$set(this.tableOption, "division", data.divisionCode);
      this.delFlagVisibleAreadiog = false;
    },
    // 获取索引值
    getIndex(index) {
      const { current = 0, size = 0 } = this.pager;
      return (current - 1) * size + (index + 1);
    },
    // 验证身份证号
    idCardValidate(rule, value, callback) {
      if (this.tableOption.cardType === "0") {
        validateIdNo(rule, value, callback);
      } else {
        callback();
      }
    },
    personTypeChange(e) {
      // 控制人员类型子类只能单选
      if (e.length > 1) {
        // 判断出新选中的node
        let diff = e.filter((item) => {
          return item.length && !this.prePersonTypes.includes(item[1]);
        });
        let last = diff[0];
        let temp = JSON.parse(JSON.stringify(e));
        temp = temp.map((item) => {
          if (item[0] == last[0]) {
            return [];
          }
          return item;
        });
        temp = temp.filter((item) => {
          return item.length;
        });
        temp.push(last);
        this.$set(this.tableOption, "jobIdList", temp);
      }
      this.prePersonTypes = [...new Set(this.tableOption.jobIdList.flat(2))];
    },
  },
};
</script>
<style lang="scss" scoped>
.userPage {
  @include formWrap(3);
  .user-top {
    .form-wrap {
      padding: 0;
    }
    .user-btn {
      min-height: 60px;
      position: relative;
      .btn {
        position: absolute;
        top: 0;
      }
      .btn:nth-of-type(1) {
        right: 65px;
      }
      .btn:nth-of-type(2) {
        right: 0;
      }
    }
  }
  .dataList {
    padding-top: 8px;
  }
  .dialogForm {
    @include formWrap(1);
  }
}
.roleTip {
  color: rgb(224, 117, 16);
}
.form-cascader {
  width: 100%;
}
.btns {
  display: flex;
  justify-content: flex-end;
  .el-button {
    margin-left: 10px;
  }
  .upload-error-list {
    h5 {
      background: #eccccc;
      line-height: 29px;
      padding-left: 10px;
      margin-top: 10px;
    }
    .error-list {
      max-height: 400px;
      overflow-y: auto;
      color: rgb(179, 11, 11);
      p {
        padding: 10px;
        border-bottom: solid 1px #ccc;
      }
    }
  }
}
</style>
<style lang="scss">
.light {
  .el-input__inner::placeholder {
    color: rgb(148, 145, 145);
  }
}
.table-person-type {
  .cell {
    display: flex;
    div {
      margin-right: 8px;
    }
  }
}
</style>
